<?php
declare (strict_types = 1);

namespace app\subscribe;

use app\Request;

class RequestLog
{

    protected $request;

    protected $data;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function onRequestStart()
    {
        // request_id = 请求时间 + 唯一id
        $request_id = date('YmdHis') . '-' . uniqid();
        $data['request_id'] = $request_id;
        $data['request_start_time'] = time();
        $data['request_method'] = $this->request->method();
        $data['request_url'] = $this->request->domain().$this->request->url();
        $data['request_ip'] = $this->request->ip();
        $data['request_param'] = json_encode($this->request->param(), JSON_UNESCAPED_UNICODE);
        $data['request_post'] = json_encode($this->request->post(), JSON_UNESCAPED_UNICODE);
        $this->data = $data;
    }

    public function onRequestEnd()
    {
        $data = $this->data;
        $end_time = time();
        $data['request_end_time'] = $end_time;
        $data['request_cost_time'] = $end_time - $data['request_start_time'];
        if (isset($this->request->user)) {
            $data['request_user_id'] = $this->request->user['id'];
        } else {
            $data['request_user_id'] = 0;
        }
        $requestLog = new \app\common\log\model\RequestLog();
        $requestLog->save($data);
    }

    // 订阅
    public function subscribe($event)
    {
        $event->listen('HttpRun', [$this, 'onRequestStart']);
        $event->listen('HttpEnd', [$this, 'onRequestEnd']);
    }
}
